import { getGeneratePlan } from '@/services/rrs/api';
import { PageContainer } from '@ant-design/pro-layout';
import { useMount } from 'ahooks';
import { Button, message, Tabs } from 'antd';
import { useModel } from '../../.umi/exports';
import './generate.less';
import GenerateLine from './GenerateLine';

const GeneratePlan = () => {
  useMount(() => {
    handleGenerate();
  });

  const { generateList, tabLableList, setGenerateAndTabList } = useModel('generate');

  const handleGenerate = async () => {
    try {
      const { code, data = [] } = await getGeneratePlan();
      if (code === '200') {
        setGenerateAndTabList(data);
      }
    } catch (error) {
      message.error('生成失败，请重试！');
    }
  };

  const renderTabChildren = (valueLists) => {
    return valueLists.map((lineItems, i) => {
      if (!lineItems.length) return;
      const renderItems = [];
      for (let i = 0; i < lineItems.length; i++) {
        renderItems.push(lineItems[i]);
        if (i === lineItems.length - 1) break;
        renderItems.push({
          startTime: lineItems[i].endTime,
          endTime: lineItems[i + 1].startTime,
          brand: '',
          id: '',
        });
      }
      const totalWidth = renderItems[renderItems.length - 1].endTime;
      return (
        <>
          <p style={{ fontWeight: 800 }}>生产线{i + 1}:</p>
          <GenerateLine
            data={renderItems.map((item, index) => ({
              width: ((item.endTime - item.startTime + 1) * 100) / totalWidth + '%',
              label: item.brand,
              id: item.id,
              startTime: index === 0 ? 0 : (item.startTime * 24 * 60 * 60) / totalWidth,
              endTime:
                index === renderItems.length - 1
                  ? 24 * 60 * 60 - 1
                  : (item.endTime * 24 * 60 * 60) / totalWidth,
            }))}
          />
          <br />
        </>
      );
    });
  };

  return (
    <PageContainer className="generatePlan">
      <div className="generatePlan-header">
        <Button type="primary" onClick={handleGenerate}>
          生成排产计划
        </Button>
      </div>

      <div className="generatePlan-content">
        <Tabs
          destroyInactiveTabPane={false}
          defaultActiveKey={tabLableList?.[0]}
          tabPosition="top"
          items={tabLableList.map((label) => {
            return {
              label: label,
              key: label,
              children: renderTabChildren(
                generateList.filter((item) => item?.[0]?.product !== label),
              ),
            };
          })}
        />
      </div>
    </PageContainer>
  );
};
export default GeneratePlan;
